<!--
 * @Author: zhangfeng
 * @Date: 2023-12-27 15:54:18
 * @LastEditTime: 2023-12-28 14:11:50
 * @LastEditors: zhangfeng
 * @Description: 
 * @FilePath: \manager\managersystem\src\views\user\module\UserDialog.vue
 * © 2023 张峰，All rights reserved.
-->
<template>
	<el-dialog v-model="dialogVisible" :title="tips" width="30%">
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			:rules="rules"
			label-width="120px"
			class="demo-ruleForm"
			:size="formSize"
			status-icon
		>
			<el-form-item label="用户名" prop="user_name">
				<el-input v-model="ruleForm.user_name" />
			</el-form-item>
			<el-form-item v-if="dialagAdd" label="密码" prop="password">
				<el-input type="password" v-model="ruleForm.password" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-form-item>
					<el-button type="primary" @click="submitForm(ruleFormRef)">
						{{ submitText }}
					</el-button>
					<el-button @click="dialogVisible = false">Cancal</el-button>
				</el-form-item>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import { useUsers } from '../../../composables/useUsers';
import { globalInjectSymbol } from '../../../utils/symbolKey';

const { successOrError } = inject(globalInjectSymbol) || {};
const tips = ref('');
const dialogVisible = ref(false);
const ruleForm = ref();
const dialagAdd = ref(false);
const { createUsers, updateUsers } = useUsers();
const emit = defineEmits<{ (e: 'getlist'): void }>();
const rules = ref<FormRules>({
	user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
});
const formSize = ref<'default' | 'small' | 'large'>('default');
const submitText = ref('create');
const ruleFormRef = ref<FormInstance>();
const resetRuleFrom = ref({
	name: '',
	description: '',
});
const submitForm = async (refs: FormInstance | undefined) => {
	if (!refs) return;
	await refs.validate(async (valid, fields) => {
		if (valid) {
			let result: AxiosResponse<ResponseData>;
			if (ruleForm.value.id) {
				result = await updateUsers(ruleForm.value);
			} else {
				result = await createUsers(ruleForm.value);
			}
			if (successOrError) {
				successOrError(result);
				dialogVisible.value = false;
			}
			emit('getlist');
		}
	});
};
const addUsers = () => {
	dialogVisible.value = true;
	ruleForm.value = JSON.parse(JSON.stringify(resetRuleFrom.value));
	submitText.value = 'create';
	dialagAdd.value = true;
};

const editUsers = (row: RoleTableData[]) => {
	dialogVisible.value = true;
	ruleForm.value = JSON.parse(JSON.stringify(row));
	submitText.value = 'update';
	dialagAdd.value = false;
};

defineExpose({
	addUsers,
	editUsers,
});
</script>

<style scoped></style>
